package com.phiture.erp.stock.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialResp;
import com.phiture.erp.basic.api.service.ErpCustomerApi;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.common.constants.ErpNoPrefixConstants;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.common.enums.ErpStockRecordBizTypeEnum;
import com.phiture.erp.common.utils.ErpNoGenerator;
import com.phiture.erp.produce.api.service.ErpProduceApi;
import com.phiture.erp.stock.core.pojo.dto.ErpStockOutPageReqDTO;
import com.phiture.erp.stock.core.pojo.dto.ErpStockOutSaveReqDTO;
import com.phiture.erp.stock.core.pojo.dto.ErpStockRecordCreateReqDTO;
import com.phiture.erp.stock.core.service.ErpStockOutReqService;
import com.phiture.erp.stock.core.service.ErpStockRecordService;
import com.phiture.erp.stock.core.service.ErpWarehouseService;
import com.phiture.erp.stock.dal.entity.ErpStockOutDO;
import com.phiture.erp.stock.dal.entity.ErpStockOutItemDO;
import com.phiture.erp.stock.dal.mapper.ErpStockOutItemMapper;
import com.phiture.erp.stock.dal.mapper.ErpStockOutMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static com.phiture.erp.common.constants.ErrorCodeConstants.*;

/**
 * ERP 领料出库单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@RequiredArgsConstructor
public class ErpStockOutReqServiceImpl implements ErpStockOutReqService {
    private final ErpStockOutMapper stockOutMapper;
    private final ErpStockOutItemMapper stockOutItemMapper;
    private final ErpNoGenerator erpNoGenerator;
    private final ErpMaterialApi materialApi;
    private final ErpWarehouseService warehouseService;
    private final ErpCustomerApi customerApi;
    private final ErpStockRecordService stockRecordService;

    private final ErpProduceApi produceApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createStockOut(ErpStockOutSaveReqDTO createReqDTO) {
        // 1.1 校验出库项的有效性
        List<ErpStockOutItemDO> stockOutItems = validateStockOutItems(createReqDTO.getItems());
        // 1.3 生成出库单号，并校验唯一性
        String no = erpNoGenerator.generate(ErpNoPrefixConstants.STOCK_OUT_REQ_NO_PREFIX);
        validateOrderNo(no);

        // 2.1 插入出库单
        ErpStockOutDO stockOut = BeanUtils.toBean(createReqDTO, ErpStockOutDO.class, in -> in
                .setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus())
                .setTotalCount(getSumValue(stockOutItems, ErpStockOutItemDO::getCount, BigDecimal::add))
                .setTotalPrice(getSumValue(stockOutItems, ErpStockOutItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO)));
        stockOutMapper.insert(stockOut);
        // 2.2 插入出库单项
        stockOutItems.forEach(o -> o.setOutId(stockOut.getId())
                .setId(null));
        stockOutItemMapper.insertBatch(stockOutItems);

        // 2.3 领料出库数量反写生产任务单的已领数量
        stockOutItems.forEach(stockOutItem -> {
            // 2.3.1 更新生产任务单的已领数量
            int result = produceApi.updateIssuedQuantity(stockOutItem.getSourceBillItemId(), stockOutItem.getCount(), stockOut.getOutType());
            ErpMaterialResp material = materialApi.getMaterial(stockOutItem.getMaterialId());
            String materialName = Objects.nonNull(material) ? material.getName(): "";
            if (result == -1) {
                throw exception(STOCK_OUT_REQ_UPDATE_FAIL_NOT_EXISTS, materialName);
            } else if (result == -2) {
                if (ErpStockRecordBizTypeEnum.REQ_OUT.getType().equals(stockOut.getOutType())) {
                    throw exception(STOCK_OUT_REQ_UPDATE_FAIL_EXCEED, materialName);
                }else if (ErpStockRecordBizTypeEnum.BACK_FLUSH_OUT.getType().equals(stockOut.getOutType())) {
                    // TODO 倒冲是异步处理的，需要记录错误，事后处理, 暂时是同步处理。
                    throw exception(BACK_FLUSH_OUT_UPDATE_FAIL_EXCEED, materialName);
                }else {
                    // 退料入库小于已领数量
                    throw exception(STOCK_OUT_RETURN_UPDATE_FAIL_LESS, materialName);
                }
            }
        });

        return stockOut.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockOut(ErpStockOutSaveReqDTO updatepageReqDTO) {
        // 1.1 校验存在
        ErpStockOutDO stockOut = validateStockOutExists(updatepageReqDTO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(stockOut.getStatus())) {
            throw exception(STOCK_OUT_REQ_UPDATE_FAIL_APPROVE, stockOut.getNo());
        }
        // 1.3 校验出库项的有效性
        List<ErpStockOutItemDO> stockOutItems = validateStockOutItems(updatepageReqDTO.getItems());

        // 2.1 更新出库单
        ErpStockOutDO updateObj = BeanUtils.toBean(updatepageReqDTO, ErpStockOutDO.class, in -> in
                .setTotalCount(getSumValue(stockOutItems, ErpStockOutItemDO::getCount, BigDecimal::add))
                .setTotalPrice(getSumValue(stockOutItems, ErpStockOutItemDO::getTotalPrice, BigDecimal::add)));
        stockOutMapper.updateById(updateObj);
        // 2.2 更新出库单项
        updateStockOutItemList(updatepageReqDTO.getId(), stockOutItems);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockOutStatus(Long id, Integer status) {
        boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status);
        // 1.1 校验存在
        ErpStockOutDO stockOut = validateStockOutExists(id);
        // 1.2 校验状态
        if (stockOut.getStatus().equals(status) && !ErpStockRecordBizTypeEnum.BACK_FLUSH_OUT_CANCEL.getType().equals(stockOut.getOutType())) {
            throw exception(approve ? STOCK_OUT_APPROVE_FAIL : STOCK_OUT_PROCESS_FAIL);
        }
        // 2. 更新状态
        int updateCount = stockOutMapper.updateByIdAndStatus(id, stockOut.getStatus(),
                new ErpStockOutDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? STOCK_OUT_APPROVE_FAIL : STOCK_OUT_PROCESS_FAIL);
        }

        // 3. 变更库存
        List<ErpStockOutItemDO> stockOutItems = stockOutItemMapper.selectListByOutId(id);
        Integer bizType;
        // 领料出库场合
        if (ErpStockRecordBizTypeEnum.REQ_OUT.getType().equals(stockOut.getOutType()) ||
                ErpStockRecordBizTypeEnum.BACK_FLUSH_OUT.getType().equals(stockOut.getOutType())||
                ErpStockRecordBizTypeEnum.BACK_FLUSH_OUT_CANCEL.getType().equals(stockOut.getOutType())) {


            if(ErpStockRecordBizTypeEnum.REQ_OUT.getType().equals(stockOut.getOutType())){
                bizType = approve ? ErpStockRecordBizTypeEnum.REQ_OUT.getType()
                        : ErpStockRecordBizTypeEnum.REQ_OUT_CANCEL.getType();
            }else{
                bizType = stockOut.getOutType();
            }

            stockOutItems.forEach(stockOutItem -> {
                BigDecimal count = approve && !ErpStockRecordBizTypeEnum.BACK_FLUSH_OUT_CANCEL.getType().equals(stockOut.getOutType()) ? stockOutItem.getCount().negate() : stockOutItem.getCount();
                stockRecordService.createStockRecord(new ErpStockRecordCreateReqDTO(
                        stockOutItem.getMaterialId(), stockOutItem.getWarehouseId(), count,
                        bizType, stockOutItem.getOutId(), stockOutItem.getId(), stockOut.getNo()));
            });
        }else {
            // 退料入库场合
                bizType = approve ? ErpStockRecordBizTypeEnum.RETURN_IN.getType()
                        : ErpStockRecordBizTypeEnum.RETURN_IN_CANCEL.getType();
            stockOutItems.forEach(stockOutItem -> {
                BigDecimal count = approve ? stockOutItem.getCount() : stockOutItem.getCount().negate();
                stockRecordService.createStockRecord(new ErpStockRecordCreateReqDTO(
                        stockOutItem.getMaterialId(), stockOutItem.getWarehouseId(), count,
                        bizType, stockOutItem.getOutId(), stockOutItem.getId(), stockOut.getNo()));

            });
        }

    }

    private List<ErpStockOutItemDO> validateStockOutItems(List<ErpStockOutSaveReqDTO.Item> list) {
        // 如果该物料为倒冲出库情况，提示不可以操作
        list.forEach(item -> {
            if (item.isBackFlushFlag()) {
                String materialName = materialApi.getMaterial(item.getMaterialId()).getName();
                throw exception(STOCK_OUT_REQ_BACK_FLUSH_NOT_SUPPORT,  materialName);
            }
        });

        // 1.1 校验产品存在
        List<ErpMaterialResp> materialList = materialApi.validMaterialList(
                convertSet(list, ErpStockOutSaveReqDTO.Item::getMaterialId));
        Map<Long, ErpMaterialResp> materialMap = convertMap(materialList, ErpMaterialResp::getId);
        // 1.2 校验仓库存在
        warehouseService.validWarehouseList(convertSet(list, ErpStockOutSaveReqDTO.Item::getWarehouseId));
        // 2. 转化为 ErpStockOutItemDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, ErpStockOutItemDO.class, item -> item
                .setMaterialUnitId(materialMap.get(item.getMaterialId()).getUnitId())
                .setTotalPrice(MoneyUtils.priceMultiply(item.getMaterialPrice(), item.getCount()))));
    }

    private void updateStockOutItemList(Long id, List<ErpStockOutItemDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpStockOutItemDO> oldList = stockOutItemMapper.selectListByOutId(id);
        List<List<ErpStockOutItemDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setOutId(id));
            stockOutItemMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            stockOutItemMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            stockOutItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpStockOutItemDO::getId));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteStockOut(List<Long> ids) {
        // 1. 校验不处于已审批
        List<ErpStockOutDO> stockOuts = stockOutMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(stockOuts)) {
            return;
        }
        stockOuts.forEach(stockOut -> {
            if (ErpAuditStatus.APPROVE.getStatus().equals(stockOut.getStatus())) {
                throw exception(STOCK_OUT_DELETE_FAIL_APPROVE, stockOut.getNo());
            }
        });

        // 2. 遍历删除，并记录操作日志
        stockOuts.forEach(stockOut -> {
            // 2.1 删除出库单
            stockOutMapper.deleteById(stockOut.getId());
            // 2.2 删除出库单项
            stockOutItemMapper.deleteByOutId(stockOut.getId());
        });
    }

    private ErpStockOutDO validateStockOutExists(Long id) {
        ErpStockOutDO stockOut = stockOutMapper.selectById(id);
        if (stockOut == null) {
            throw exception(STOCK_OUT_NOT_EXISTS);
        }
        return stockOut;
    }

    @Override
    public ErpStockOutDO getStockOut(Long id) {
        return stockOutMapper.selectById(id);
    }

    @Override
    public PageResult<ErpStockOutDO> getStockOutPage(ErpStockOutPageReqDTO pageReqDTO) {
        MPJLambdaWrapperX<ErpStockOutDO> query = new MPJLambdaWrapperX<ErpStockOutDO>()
                .likeIfPresent(ErpStockOutDO::getNo, pageReqDTO.getNo())
                .eqIfPresent(ErpStockOutDO::getCustomerId, pageReqDTO.getCustomerId())
                .betweenIfPresent(ErpStockOutDO::getOutTime, pageReqDTO.getOutTime())
                .eqIfPresent(ErpStockOutDO::getStatus, pageReqDTO.getStatus())
                .likeIfPresent(ErpStockOutDO::getRemark, pageReqDTO.getRemark())
                .eqIfPresent(ErpStockOutDO::getCreator, pageReqDTO.getCreator())
                .eqIfPresent(ErpStockOutDO::getOutType, pageReqDTO.getOutType())
                .orderByDesc(ErpStockOutDO::getId);
        if (pageReqDTO.getWarehouseId() != null || pageReqDTO.getMaterialId() != null) {
            query.leftJoin(ErpStockOutItemDO.class, ErpStockOutItemDO::getOutId, ErpStockOutDO::getId)
                    .eq(pageReqDTO.getWarehouseId() != null, ErpStockOutItemDO::getWarehouseId, pageReqDTO.getWarehouseId())
                    .eq(pageReqDTO.getMaterialId() != null, ErpStockOutItemDO::getMaterialId, pageReqDTO.getMaterialId())
                    .groupBy(ErpStockOutDO::getId); // 避免 1 对多查询，产生相同的 1
        }
        return stockOutMapper.selectJoinPage(pageReqDTO, ErpStockOutDO.class, query);
    }

    // ==================== 出库项 ====================

    @Override
    public List<ErpStockOutItemDO> getStockOutItemListByOutId(Long outId) {
        return stockOutItemMapper.selectListByOutId(outId);
    }

    @Override
    public List<ErpStockOutItemDO> getStockOutItemListByOutIds(Collection<Long> outIds) {
        if (CollUtil.isEmpty(outIds)) {
            return Collections.emptyList();
        }
        return stockOutItemMapper.selectListByOutIds(outIds);
    }

    private void validateOrderNo(String orderNo){
        boolean exists = stockOutMapper.exists(
                Wrappers.lambdaQuery(ErpStockOutDO.class)
                        .eq(ErpStockOutDO::getNo, orderNo)
                        .eq(ErpStockOutDO::getDeleted, Boolean.FALSE)
        );
        if(exists){
            throw exception(STOCK_OUT_NO_EXISTS);
        }
    }

}